package leetcode.weekly.week327;

//Solution3Test
public class Solution3 {

	public boolean isItPossible(String word1, String word2) {
		int[] h1 = new int[26];
		int[] h2 = new int[26];
		for (int i = 0; i < word1.length(); i++) {
			h1[word1.charAt(i) - 'a']++;
		}
		for (int i = 0; i < word2.length(); i++) {
			h2[word2.charAt(i) - 'a']++;
		}
		int a = 0, b = 0;
		for (int i = 0; i < 26; i++) {
			if (h1[i] != 0) {
				a++;
			}
		}
		for (int i = 0; i < 26; i++) {
			if (h2[i] != 0) {
				b++;
			}
		}
		for (int i = 0; i < 26; i++) {
			if (h1[i] == 0) {
				continue;
			}
			for (int j = 0; j < 26; j++) {
				if (h2[j] == 0) {
					continue;
				}
				int na = --h1[i] == 0 ? a - 1 : a;
				if (h1[j] == 0) {
					na += 1;
				}
				int nb = --h2[j] == 0 ? b - 1 : b;
				if (h2[i] == 0) {
					nb += 1;
				}
				if (na == nb) {
					return true;
				}
				h1[i] += 1;
				h2[j] += 1;
			}
		}
		return false;
	}
}
